package javaStu.producerAndConsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产消费模式
 * 用两个线程，一个输出字母，一个输出数字，交替输出1A2B3C4D5E...26Z
 *
 * @author: leiwenkang
 * @date: 2020/7/13
 * @time: 20:22
 */
public class ProducerAndConsumer_LockCondition {

    public static void main(String[] args) {
        char[] ch1 = "1234567".toCharArray();
        char[] ch2 = "ABCDEFG".toCharArray();

        Lock lock = new ReentrantLock();
        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();

        new Thread(() -> {
            try {
                lock.lock();
                for (char c : ch1) {
                    System.out.print(c);
                    condition2.signal();
                    condition1.await();

                    condition2.signal();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1").start();


        new Thread(() -> {
            try {
                lock.lock();
                for (char c : ch2) {
                    System.out.print(c);

                    condition1.signal();
                    condition2.await();

                    condition1.signal();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t2").start();
    }

}
